package com.heima.behavio.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.api.R;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.behavio.mapper.BhLikeMapper;

import com.heima.behavio.service.BhLikeService;
import com.heima.common.redis.CacheService;
import com.heima.model.admin.pojo.AdUser;
import com.heima.model.behavior.dtos.BehaviorDto;
import com.heima.model.behavior.dtos.LikesBehaviorDto;
import com.heima.model.behavior.dtos.LoadBehaviorDto;
import com.heima.model.behavior.pojos.BhLike;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.utils.common.ApThreadLocalUtil;
import com.heima.utils.common.WmThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.kafka.common.protocol.types.Field;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.sql.Wrapper;
import java.util.ArrayDeque;
import java.util.Set;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author dlc
 */
@Slf4j
@Service
@Transactional
public class BhLikeServiceImpl extends ServiceImpl<BhLikeMapper, BhLike> implements BhLikeService {

    @Autowired
    private CacheService cacheService;
    @Autowired
    private BhLikeMapper bhLikeMapper;

    @Override
    public ResponseResult LikesBehavior(LikesBehaviorDto dto) {
        //.0获取当前操作的用户
        ApUser user = ApThreadLocalUtil.getUser();
        //1判断参数是否合规
 ;
        if (dto==null){
            //参数不存在,返回404
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //2.判断参数dto中的Operation的值,如果0是新增点赞
            if (dto.getOperation()==0){
                //2.1设置用户
                BhLike bhLike = new BhLike();
                bhLike.setApUserId((long)user.getId());
                //设置文章id
                bhLike.setArticleId(dto.getArticleId());
                //2.2设置点赞类型type 0文章  1动态   2评论
                bhLike.setType(dto.getType());
                //2.3插入数据
                bhLikeMapper.insert(bhLike);



                //3将数据持计划到redis中
                saveBehaviorToCac(dto,user);

            }
            //3.如果2.判断参数dto中的Operation的值,如果0是新增点赞
            if (dto.getOperation()==1 ){

                LambdaQueryWrapper<BhLike> wrapper = new LambdaQueryWrapper<>();
                wrapper.eq(BhLike::getArticleId,dto.getArticleId())
                        .eq(BhLike::getApUserId,user.getId())
                        .eq(BhLike::getType,dto.getType());
                bhLikeMapper.delete(wrapper);
                //数据持久化到redis中
                saveBehaviorToCac(dto,user);


            }


            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);

    }

    @Override
    public ResponseResult loadArticleBehavior(LoadBehaviorDto dto) {
        BehaviorDto behaviorDto = new BehaviorDto();
        //默认返回全是false
        behaviorDto.setIslike(false);
        behaviorDto.setIscollection(false);
        behaviorDto.setIsfollow(false);
        behaviorDto.setIsunlike(false);

        //1.获取当前用户
        ApUser user = ApThreadLocalUtil.getUser();
        //2从redis获取文章的点赞\喜不喜欢\收藏的状态
        String key=dto.getArticleId()+"_"+user.getId();
        String behaviorDtoString = cacheService.get(key);
            //如果value为空返回前端空数据
        if (StringUtils.isBlank(behaviorDtoString)){
            return ResponseResult.okResult( BehaviorDto.class);
        }
         behaviorDto = JSON.parseObject(behaviorDtoString, BehaviorDto.class);

        //2.需要设置是否是关注了isfollow字段
        String key2=dto.getAuthorId()+"_"+user.getId();
        String value = cacheService.get(key2);
        BehaviorDto behaviorDto1 = JSON.parseObject(value, BehaviorDto.class);

        //2.1判断是否进行了关注
        if (behaviorDto==null){
            //没进行关注,将BehaviorDto的isfollow更新为false返回
            behaviorDto.setIsfollow(false);
            return ResponseResult.okResult(behaviorDto);

        }

        //3.两个将关注了作者,将两个beha合并返回
        behaviorDto.setIsfollow(behaviorDto1.getIsfollow());

        return ResponseResult.okResult(behaviorDto);


    }

    /**
     * 将点赞行为缓存到redis数据中
     * @param dto
     * @param user
     */

    private void saveBehaviorToCac(LikesBehaviorDto dto, ApUser user) {
        //定义flage
        boolean flag=false;

        //3.1定义缓存的key
        String key=dto.getArticleId()+"_"+user.getId();
        //3.2查询到value
        BehaviorDto behaviorDto = new BehaviorDto();
        String value = cacheService.get(key);
        if (value != null) {

            behaviorDto = JSON.parseObject(value, BehaviorDto.class);
        }
        //3.3更改值
        if (dto.getOperation() == 0){
            flag=true;
        }

        behaviorDto.setIslike(flag);
        //3.4删除缓存
        cacheService.delete(key);
        //3.5更新缓存
        value= JSON.toJSONString(behaviorDto);
        cacheService.set(key,value);
    }




}
